import Foundation
import Combine
import Network

// 小车指令类型
enum CarCommand: String {
    case forward = "F"    // 前进
    case backward = "B"   // 后退
    case left = "L"       // 左转
    case right = "R"      // 右转
    case stop = "S"       // 停止
    case speedUp = "+"    // 加速
    case speedDown = "-"  // 减速
    case takePhoto = "P"  // 拍照
    case startVideo = "V" // 开始录像
    case stopVideo = "X"  // 停止录像
    case getSensorData = "D" // 获取传感器数据
}

// TCP小车服务
class TCPCarService: ObservableObject {
    // 连接状态
    @Published var isConnected: Bool = false
    @Published var isConnecting: Bool = false
    @Published var connectionError: String? = nil
    @Published var versionInfo: String? = nil
    
    // 小车状态
    @Published var speed: Int = 0 { // 0-100
        didSet {
            if oldValue != speed {
                print("速度更新: \(oldValue) -> \(speed)")
            }
        }
    }
    @Published var direction: String = "停止" {
        didSet {
            if oldValue != direction {
                print("方向更新: \(oldValue) -> \(direction)")
            }
        }
    }
    @Published var batteryLevel: Int = 100 {
        didSet {
            if oldValue != batteryLevel {
                print("电池更新: \(oldValue) -> \(batteryLevel)")
            }
        }
    }
    @Published var temperature: Double = 0 {
        didSet {
            if abs(oldValue - temperature) > 0.1 {
                print("温度更新: \(oldValue) -> \(temperature)")
            }
        }
    }
    @Published var humidity: Double = 0 {
        didSet {
            if abs(oldValue - humidity) > 0.1 {
                print("湿度更新: \(oldValue) -> \(humidity)")
            }
        }
    }
    
    // 调试模式标志
    @Published var isDebugMode: Bool = false
    
    // 连接信息
    private var ipAddress: String = ""
    private var port: UInt16 = 6000 // 指令端口
    private var videoPort: UInt16 = 6500 // 视频端口
    
    // TCP连接
    private var connection: NWConnection?
    private var connectionSettings: ConnectionSettings?
    
    // 接收数据队列
    private let receiveQueue = DispatchQueue(label: "com.mycar.receiveQueue")
    
    private var isInitDone = false
    private var carType: UInt8 = 0x01 // 可配置
    
    // 初始化
    init(connectionSettings: ConnectionSettings? = nil) {
        self.connectionSettings = connectionSettings
        
        if let settings = connectionSettings {
            self.ipAddress = settings.ipAddress
            if let portNum = UInt16(settings.port) {
                self.port = portNum
            }
            if let videoPortNum = UInt16(settings.cameraPort) {
                self.videoPort = videoPortNum
            }
        }
    }
    
    // 更新连接设置
    func updateConnectionSettings(_ settings: ConnectionSettings) {
        self.connectionSettings = settings
        self.ipAddress = settings.ipAddress
        if let portNum = UInt16(settings.port) {
            self.port = portNum
        }
        if let videoPortNum = UInt16(settings.cameraPort) {
            self.videoPort = videoPortNum
        }
    }
    
    // 设置调试模式
    func setDebugMode(_ enabled: Bool) {
        isDebugMode = enabled
        if enabled {
            // 模拟连接成功
            isConnected = true
            
            // 初始化模拟数据
            speed = 50
            direction = "停止"
            batteryLevel = 85
            temperature = 24.5
            humidity = 60.0
        }
    }
    
    // 连接到小车
    func connect(completion: @escaping (Bool) -> Void) {
        guard !ipAddress.isEmpty else {
            connectionError = "IP地址不能为空"
            completion(false)
            return
        }
        isConnecting = true
        connectionError = nil
        isInitDone = false
        // 1. HTTP GET /init
        let url = URL(string: "http://\(ipAddress):6500/init")!
        let task = URLSession.shared.dataTask(with: url) { [weak self] _, response, error in
            guard let self = self else { return }
            if let error = error {
                DispatchQueue.main.async {
                    self.connectionError = "初始化失败: \(error.localizedDescription)"
                    self.isConnecting = false
                    completion(false)
                }
                return
            }
            // 2. 延迟500ms后建立TCP连接
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.connectTCP(completion: completion)
            }
        }
        task.resume()
    }
    
    private func connectTCP(completion: @escaping (Bool) -> Void) {
        let host = NWEndpoint.Host(ipAddress)
        let port = NWEndpoint.Port(rawValue: self.port)!
        let tcpOptions = NWProtocolTCP.Options()
        tcpOptions.connectionTimeout = 5
        let parameters = NWParameters(tls: nil, tcp: tcpOptions)
        parameters.allowLocalEndpointReuse = true
        connection = NWConnection(host: host, port: port, using: parameters)
        connection?.stateUpdateHandler = { [weak self] state in
            guard let self = self else { return }
            switch state {
            case .ready:
                self.isConnected = true
                self.isConnecting = false
                self.startReceiving()
                // 3. 连接成功后发送版本/电池查询
                self.sendVersionQuery()
                self.sendBatteryQuery()
                // 4. 开启视频流（可在UI层处理）
                completion(true)
            case .failed(let error):
                self.connectionError = "连接失败: \(error)"
                self.isConnected = false
                self.isConnecting = false
                self.disconnect()
                completion(false)
            case .cancelled:
                self.isConnected = false
                self.isConnecting = false
                completion(false)
            default:
                break
            }
        }
        connection?.start(queue: .main)
        // 超时处理
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
            if self?.isConnecting == true {
                self?.connectionError = "连接超时"
                self?.isConnected = false
                self?.isConnecting = false
                self?.disconnect()
                completion(false)
            }
        }
    }
    
    // 断开连接
    func disconnect() {
        if isDebugMode {
            // 调试模式下只需要重置状态
            isConnected = false
            return
        }
        
        connection?.cancel()
        connection = nil
        isConnected = false
    }
    
    // 发送协议命令
    func sendCarCommand(functionCode: UInt8, data: [UInt8] = []) {
        let cmd = CarProtocolBuilder.buildCommand(carType: carType, functionCode: functionCode, data: data)
        sendData(cmd) { _ in }
    }
    
    // 发送版本查询
    func sendVersionQuery() {
        sendCarCommand(functionCode: 0x01)
    }
    // 发送电池电压查询
    func sendBatteryQuery() {
        sendCarCommand(functionCode: 0x02)
    }
    // 发送灯光控制
    func sendLightControl(on: Bool) {
        let value: UInt8 = on ? 0x01 : 0x00
        sendCarCommand(functionCode: 0x10, data: [value])
    }
    
    // 发送命令
    func sendCommand(_ command: CarCommand, parameter: Int = 0) {
        if isDebugMode {
            // 调试模式下模拟命令处理
            handleDebugCommand(command, parameter: parameter)
            return
        }
        
        guard isConnected, let connection = connection else {
            print("未连接，无法发送命令")
            return
        }
        
        var commandString = command.rawValue
        if parameter > 0 {
            commandString += String(parameter)
        }
        commandString += "\n"
        
        guard let data = commandString.data(using: .utf8) else {
            print("命令转换为数据失败")
            return
        }
        
        connection.send(content: data, completion: .contentProcessed { error in
            if let error = error {
                print("发送命令失败: \(error)")
            } else {
                print("命令发送成功: \(commandString)")
            }
        })
    }
    
    // 调试模式下处理命令
    private func handleDebugCommand(_ command: CarCommand, parameter: Int = 0) {
        print("[调试模式] 处理命令: \(command.rawValue)\(parameter > 0 ? String(parameter) : "")")
        
        switch command {
        case .forward:
            direction = "前进"
            // 模拟耗电
            batteryLevel = max(1, batteryLevel - 1)
        case .backward:
            direction = "后退"
            batteryLevel = max(1, batteryLevel - 1)
        case .left:
            direction = "左转"
            batteryLevel = max(1, batteryLevel - 1)
        case .right:
            direction = "右转"
            batteryLevel = max(1, batteryLevel - 1)
        case .stop:
            direction = "停止"
        case .speedUp:
            speed = min(100, speed + 10)
        case .speedDown:
            speed = max(0, speed - 10)
        case .getSensorData:
            // 模拟传感器数据波动
            temperature = 24.0 + Double.random(in: -2.0...2.0)
            humidity = 60.0 + Double.random(in: -5.0...5.0)
            batteryLevel = max(1, batteryLevel - Int.random(in: 0...1))
        default:
            break
        }
    }
    
    // 发送数据
    func sendData(_ data: Data, completion: @escaping (Bool) -> Void) {
        if isDebugMode {
            // 调试模式下模拟成功
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                completion(true)
            }
            return
        }
        
        guard isConnected, let connection = connection else {
            completion(false)
            return
        }
        
        connection.send(content: data, completion: .contentProcessed { error in
            if let error = error {
                print("发送数据失败: \(error)")
                completion(false)
            } else {
                completion(true)
            }
        })
    }
    
    // 开始监听数据
    private func startReceiving() {
        guard let connection = connection else { return }
        
        receiveMessage(on: connection)
    }
    
    // 接收消息
    private func receiveMessage(on connection: NWConnection) {
        connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] (data, _, isComplete, error) in
            guard let self = self else { return }
            
            if let data = data, !data.isEmpty {
                // 处理收到的数据
                self.processReceivedData(data)
            }
            
            if isComplete {
                // 连接已完成
                self.disconnect()
            } else if let error = error {
                // 接收错误
                print("接收数据错误: \(error)")
                self.disconnect()
            } else {
                // 继续接收数据
                self.receiveMessage(on: connection)
            }
        }
    }
    
    // 处理接收到的数据
    private func processReceivedData(_ data: Data) {
        // 在后台线程处理数据解析，避免阻塞主线程
        DispatchQueue.global(qos: .utility).async { [weak self] in
            guard let self = self else { return }
            
            guard let message = String(data: data, encoding: .utf8) else {
                print("无法解析收到的数据")
                return
            }
            
            print("收到数据: \(message)")
            let parts = message.components(separatedBy: ";")
            
            // 批量收集需要更新的状态
            var updates: [String: Any] = [:]
            
            for part in parts {
                let keyValue = part.components(separatedBy: ":")
                if keyValue.count == 2 {
                    let key = keyValue[0]
                    let value = keyValue[1]
                    
                    switch key {
                    case "T":
                        if let temp = Double(value) { updates["temperature"] = temp }
                    case "H":
                        if let humid = Double(value) { updates["humidity"] = humid }
                    case "B":
                        if let battery = Int(value) { updates["batteryLevel"] = battery }
                    case "S":
                        if let spd = Int(value) { updates["speed"] = spd }
                    case "D":
                        let direction: String
                        switch value {
                        case "F": direction = "前进"
                        case "B": direction = "后退"
                        case "L": direction = "左转"
                        case "R": direction = "右转"
                        case "S": direction = "停止"
                        default: direction = "未知"
                        }
                        updates["direction"] = direction
                    case "VER":
                        updates["versionInfo"] = value.trimmingCharacters(in: .whitespacesAndNewlines)
                    case "BAT":
                        if let v = Int(value.trimmingCharacters(in: .whitespacesAndNewlines)) {
                            updates["batteryLevel"] = v
                        }
                    default:
                        break
                    }
                }
            }
            
            // 批量更新UI
            DispatchQueue.main.async {
                if let temp = updates["temperature"] as? Double {
                    self.temperature = temp
                }
                if let humid = updates["humidity"] as? Double {
                    self.humidity = humid
                }
                if let battery = updates["batteryLevel"] as? Int {
                    self.batteryLevel = battery
                }
                if let spd = updates["speed"] as? Int {
                    self.speed = spd
                }
                if let direction = updates["direction"] as? String {
                    self.direction = direction
                }
                if let version = updates["versionInfo"] as? String {
                    self.versionInfo = version
                }
            }
        }
    }
    
    // 控制小车移动
    func moveForward() { sendCommand(.forward) }
    func moveBackward() { sendCommand(.backward) }
    func turnLeft() { sendCommand(.left) }
    func turnRight() { sendCommand(.right) }
    func stop() { sendCommand(.stop) }
    
    // 控制速度
    func increaseSpeed() { sendCommand(.speedUp) }
    func decreaseSpeed() { sendCommand(.speedDown) }
    
    // 相机控制
    func takePhoto() { sendCommand(.takePhoto) }
    func startVideoRecording() { sendCommand(.startVideo) }
    func stopVideoRecording() { sendCommand(.stopVideo) }
    
    // 请求传感器数据更新
    func requestSensorData() { sendCommand(.getSensorData) }
} 
